import os
from config_rpm_maker import segment, config
from config_rpm_maker.segment import OVERLAY_ORDER
from pysvn import ClientError


class HostRpmBuilder(object):

    def __init__(self, hostname, revision, work_dir, svn_service):
        self.hostname = hostname
        self.revision = revision
        self.work_dir = work_dir
        self.config_rpm_prefix = config.get('config_rpm_prefix')
        self.host_config_dir = os.path.join(self.work_dir, self.config_rpm_prefix + '-' + self.hostname)
        self.svn_service = svn_service

    def build(self):
        print "Building config rpm for host %s" % (self.hostname)

        if os.path.exists(self.host_config_dir):
            raise Exception("ERROR: '%s' exists already whereas I should be creating it now." % self.host_config_dir)

        os.mkdir(self.host_config_dir)

        svn_log_file = open(os.path.join(self.work_dir, self.hostname + '.svnlog'), 'w')
        try:
            overall_requires = []
            overall_provides = []
            for segment in OVERLAY_ORDER:
                exported_paths, requires, provides = self._overlay_segment(segment, svn_log_file)
                overall_requires += requires
                overall_provides += provides

        finally:
            svn_log_file.close()

    def _overlay_segment(self, segment, out):
        requires = []
        provides = []
        exported_paths = []
        for svn_path in segment.get_svn_paths(self.hostname):
            try:
                exported_paths = self.svn_service.export(svn_path, self.host_config_dir, self.revision, out)
                requires += self._parse_dependency_file(os.path.join(self.host_config_dir, 'VARIABLES', 'RPM_REQUIRES'))
                provides += self._parse_dependency_file(os.path.join(self.host_config_dir, 'VARIABLES', 'RPM_PROVIDES'))
            except ClientError as e:
                pass

        return exported_paths, requires, provides

    def _parse_dependency_file(self, path):
        if os.path.exists(path):
            f = open(path)
            try:
                content = f.read()
                return [item for line in content.split('\n') for item in line.split(',')]
            finally:
                f.close()

        return []

